// dart
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:webview_flutter/webview_flutter.dart';

import '../../pay_pages/result_payment/result_payment_zhifu_page.dart';

class WebViewExample extends StatefulWidget {
  final String url;
  final String outTradeNo;
  const WebViewExample({super.key, required this.url, required this.outTradeNo});

  @override
  State<WebViewExample> createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<WebViewExample> {
  late final WebViewController _controller;
  var loadingProgress = 0;

  @override
  void initState() {
    super.initState();
    // 可选：在需要时为 Android 做额外初始化（根据 webview_flutter 版本决定是否需要）
    // if (Platform.isAndroid) WebView.platform = SurfaceAndroidWebView();
    _controller = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setNavigationDelegate(NavigationDelegate(
        onProgress: (int progress) {
          setState(() => loadingProgress = progress);
        },
        onPageStarted: (String url) {},
        onPageFinished: (String url) {},
        onNavigationRequest: (NavigationRequest request) {
            try {
              final url = request.url;
              if(url.contains("https://www.baidu.com/")){
                Get.offNamed(
                  '${ResultPaymentZhifuPage.path}?buyNow=1&outTradeNo=${widget.outTradeNo}',
                  arguments: {
                    'buyNow': '1',
                    "outTradeNo": widget.outTradeNo,
                  },
                );
                return NavigationDecision.prevent; // 阻止跳转
              }
            } catch (e) {
              debugPrint('解析 URL 错误: $e');
            }
          return NavigationDecision.navigate;
        },
      ))
      ..loadRequest(Uri.parse(widget.url));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: [
          WebViewWidget(controller: _controller),
          if (loadingProgress < 100)
            LinearProgressIndicator(
              value: loadingProgress / 100,
              backgroundColor: Colors.transparent,
            ),
        ],
      ),
    );
  }
}